<?php
class Admin_PluginController extends Main_Controller_AdminAction
{
	/**
	 * @var string
	 */
	const PAGER_NAME_PLUGIN = 'Admin_PluginPager';
	
	/**
	 * @var App_Admin_Form_PluginEdit
	 */
	private $_formPluginEdit;
	
	/**
	 * @var App_Admin_Service_Plugin
	 */
	private $_servicePlugin;
	
	/**
	 * @return void
	 */
	public function init() 
	{
		$this->_formPluginEdit = Main_Form::factory('Admin_Form_PluginEdit');
		$this->_servicePlugin = new App_Admin_Service_Plugin();
		
		parent::init();
	}
	
	/**
	 * @return render
	 */
	public function pluginListAction()
	{
		return $this->render();
	}
	
	/**
	 * @return render
	 */
	public function pluginAddAction() 
	{
		$form = $this->_formPluginEdit;
		
		if ($this->_request->isPost()) {
			$data = $this->_getAllParams();
            if ($form->isValid($data)) {
 		 		$this->_servicePlugin->insertItem($data);
 		 		return $this->_redirect('/admin/plugin/plugin.list' . Main_Const::getSeriveUrlStr());
            }
		}    
		
		$this->view->form = $form;
		return $this->render();
	}
	
	/**
	 * @return render
	 */
	public function pluginEditAction() 
	{
		$pluginId = $this->_getParam('id');
		
		$form = $this->_formPluginEdit;
		
		if (! $this->_request->isPost()) {
			$dataDb = $this->_servicePlugin->getItemById($pluginId);
			$form->setFormValues($dataDb);
		} else {
			$data = $this->_getAllParams();
            if ($form->isValid($data)) {
 		 		$this->_servicePlugin->updateItem($data, $pluginId);
 		 		return $this->_redirect('/admin/plugin/plugin.list' . Main_Const::getSeriveUrlStr());      		    			
            }
		}   
		
		$this->view->form = $form;
		return $this->render();
	}
	
	
	/**
	 * @return json
	 */
	public function ajaxPagerPluginAction()
	{
	    if (!$this->_request->isXmlHttpRequest()) {
            $this->_response->setHttpResponseCode(404)->sendHeaders();
            return $this->_redirect('/error/error');
        }
        
     	$pager = Main_Pager::factory('Admin_Pager_Plugin', self::PAGER_NAME_PLUGIN); 
     	
     	$result = $pager->getResponse($_REQUEST);

     	$this->_helper->json($result);   
	}
	

}
